package com.app.ui;

import javax.swing.*;
import java.awt.*;

public class PromptStyler {
  private Color backgroundColor;
  private Color textColor;
  private Font font;
  private boolean isDarkTheme;

  public PromptStyler() {
    // 检测系统主题
    detectSystemTheme();
  }

  /**
   * 检测系统主题并相应设置样式
   */
  public void detectSystemTheme() {
    // 获取当前系统的文本背景色
    Color background = UIManager.getColor("Panel.background");
    if (background != null) {
      // 计算颜色的亮度，亮度低说明是暗色主题
      double brightness = (0.299 * background.getRed() +
          0.587 * background.getGreen() +
          0.114 * background.getBlue()) / 255;
      isDarkTheme = brightness < 0.5;
    } else {
      // 默认为false
      isDarkTheme = false;
    }

    // 根据检测到的主题设置颜色
    if (isDarkTheme) {
      setDarkTheme();
    } else {
      setLightTheme();
    }
  }

  /**
   * 设置暗色主题样式
   */
  public void setDarkTheme() {
    this.backgroundColor = new Color(30, 30, 30);
    this.textColor = new Color(220, 220, 220);
    this.font = new Font("Consolas", Font.PLAIN, 14);
    this.isDarkTheme = true;
  }

  /**
   * 设置亮色主题样式
   */
  public void setLightTheme() {
    this.backgroundColor = Color.WHITE;
    this.textColor = Color.BLACK;
    this.font = new Font("Consolas", Font.PLAIN, 14);
    this.isDarkTheme = false;
  }

  public void applyStyles(JTextArea textArea) {
    textArea.setBackground(backgroundColor);
    textArea.setForeground(textColor);
    textArea.setFont(font);
    textArea.setCaretColor(textColor);
  }

  public void applyStyles(JTextField textField) {
    textField.setBackground(backgroundColor);
    textField.setForeground(textColor);
    textField.setFont(font);
    textField.setCaretColor(textColor);

    if (isDarkTheme) {
      textField.setBorder(BorderFactory.createLineBorder(new Color(70, 70, 70)));
    } else {
      textField.setBorder(BorderFactory.createLineBorder(new Color(180, 180, 180)));
    }
  }

  public void setBackgroundColor(Color backgroundColor) {
    this.backgroundColor = backgroundColor;
  }

  public void setTextColor(Color textColor) {
    this.textColor = textColor;
  }

  public void setFont(Font font) {
    this.font = font;
  }

  public boolean isDarkTheme() {
    return isDarkTheme;
  }
}